using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//
//    No MAGIC numbers
//

static class Constants {
    public const float randomSizeUpOffset = 1.5f;
    public const float randomSizeLowOffset = 0.6f;
}

public class OtherCircle : MonoBehaviour {
    Rigidbody2D rb;
    public SpriteRenderer[] spritelist;
    private int spriteidx;

    // [HideInInspector]
    public float circleSize;

    public float colliderRatio;

    // Start is called before the first frame update
    void Start() {
        rb = GetComponent<Rigidbody2D>();
        do {
            rb.velocity = new Vector2(Random.Range(-2, 2), Random.Range(-2, 2));
        } while (rb.velocity == new Vector2(0, 0));
        // 防止小球静止
    }

    // Update is called once per frame
    void Update() {
        
    }

    public void SpawnCircle(float playerSize) {
        CircleCollider2D cc2d = GetComponent<CircleCollider2D>();
        circleSize = Random.Range(
            playerSize * Constants.randomSizeUpOffset,
            playerSize * Constants.randomSizeLowOffset
        );

        // 调整碰撞箱
        cc2d.radius = circleSize * colliderRatio;
        transform.localScale = Vector3.one * circleSize;
    }

    private void OnTriggerEnter2D(Collider2D collision) {
        //与其他小球碰撞
        if (collision.gameObject.CompareTag("OtherCircle")) {
            // Debug.Log("Crash");
            if (collision.GetComponent<OtherCircle>() != null 
                && circleSize > collision.GetComponent<OtherCircle>().circleSize) {
                Destroy(collision.gameObject);
                Grow(collision.GetComponent<OtherCircle>().circleSize);
            }
            else {
                Destroy(gameObject);
            }
        }

        // 资源回收
        if (collision.gameObject.CompareTag("BackGround")) {
            Destroy(gameObject);
        }
    }

    void Grow(float upValue) {
        circleSize += upValue / 5f;
        transform.localScale = Vector3.one * circleSize;
    }

    private void FixedUpdate() {

    }
}
